package com.leo.oplayer.service;


import java.util.ArrayList;
import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.leo.oplayer.dao.ConfigCenter;
import com.leo.oplayer.util.Constancts;
import com.leo.oplayer.util.PersonUtil;
import com.leo.oplayer.view.AlarmAlert;

/**
 * 定时执行检查。看哪些亲密联系人好久没联系了
 * @author <a href='mailto:zhongqi@mail.com'>Leo</a>
 * @data 2010-3-10
 */
public class CheckAlarm extends BroadcastReceiver {
	
	private ContactService service;

	@Override
	public void onReceive(Context context, Intent intent) {
		
		Log.d("CheckAlarm", "onReceive CheckOvertimeContacts");
		
		if(service == null){
			service = new ContactService(context);	
			Log.d("CheckAlarm", "create ContactService!!!!!!");
		}
		
		//获取配置的未联系间隔
		int spanDay = Integer.valueOf(ConfigCenter.getValue(context, Constancts.KEY_MAX_NOCONTACT_DAY, "7"));		
		
		Log.d("CheckAlarm", "before select contacts");		
		
		List<String> retPersons = new ArrayList<String>();
		
		retPersons = service.checkLongNoContacts(spanDay);
		
		//如果存在提醒人
		if(!retPersons.isEmpty()){
			StringBuffer sb = new StringBuffer();
			for(String personId: retPersons){				
				String name = PersonUtil.findNameById(context, personId);
				sb.append(name).append(" ,");
			} 
			
			String contacts = sb.toString();
			//去掉最后一个逗号
			if(contacts.endsWith(",")){
				contacts.substring(0, contacts.length()-1);
			}
			
			/* create Intent，调用AlarmAlert.class */
		    Intent i = new Intent(context, AlarmAlert.class);
		        
		    Bundle bundleRet = new Bundle();
		    bundleRet.putString("STR_CALLER", "");
		    i.putExtras(bundleRet);
		    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		    i.putExtra("contacts", contacts);
		    context.startActivity(i);
		}	
		
	}

}
